package com.lumm.services.impl;

import com.lumm.dao.*;
import com.lumm.model.*;
import com.lumm.services.DynamicService;
import com.lumm.services.MessageService;
import com.lumm.services.UserService;
import com.lumm.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("DynamicServiceImpl")
public class DynamicServiceImpl implements DynamicService {

    @Autowired
    private DynamicMapper dynamicMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FollowingMapper followingMapper;

    @Autowired
    private DetailsMapper detailsMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public int sendDynamic(int userId, String content) {

        Dynamic dynamic = new Dynamic();
        dynamic.setUserId(userId);
        dynamic.setContent(content);
        dynamic.setPublishTime(new Date(System.currentTimeMillis()));
        if (dynamicMapper.insertSelective(dynamic) == 0)
            return 0;
        return 1;
        //return null;
    }

    @Override
    public List<Dynamic> getFoundList(int userId, int offset, int count) {

        List<RecommendItem> recommendItems = getFollowingList(userId, 0, 20);

        List<Dynamic> dynamics = new ArrayList<>();
        List<Integer> dynamicIds = new ArrayList<>();
        dynamicIds.add(0);

        DynamicExample dynamicExample = new DynamicExample();
        dynamicExample.setOrderByClause("publish_time DESC limit 1");

        for (RecommendItem recommendItem : recommendItems) {
            dynamicExample.clear();
            dynamicExample.setOrderByClause("publish_time DESC limit 1");
            dynamicExample.or().andUserIdEqualTo(recommendItem.getUserId());
            List<Dynamic> dList = dynamicMapper.selectByExample(dynamicExample);
            if (dList == null || dList.size() == 0)
                continue;
            dynamicIds.add(dList.get(0).getDynamicId());
            dynamics.add(dList.get(0));
        }
        dynamicExample.clear();
        dynamicExample.setOrderByClause("publish_time DESC limit " + (20 - dynamics.size()));

        dynamicExample.or().andUserIdNotIn(dynamicIds);

        dynamics.addAll(dynamicMapper.selectByExampleWithBLOBs(dynamicExample));

        for (Dynamic dynamic:dynamics){

            User user=userMapper.selectByPrimaryKey(dynamic.getUserId());
            user.setPassword(null);
            dynamic.setUser(user);

        }

        return dynamics;
    }

    /*@Override
    public List<RecommendItem> getFollowingUserList(int userId, String orderBy, int offset, int count) {

        FollowingExample followingExample = new FollowingExample();

        followingExample.setOrderByClause(orderBy + " limit " + offset + " , " + count);
        followingExample.or().andUserFollowingEqualTo(userId);
        List<Following> followings = followingMapper.selectByExample(followingExample);

        List<RecommendItem> recommendItems = new ArrayList<>();
        for (Following following : followings) {

            User oneUser = userMapper.selectByPrimaryKey(following.getUserFollowed());

            DetailsWithBLOBs details = detailsMapper.selectByPrimaryKey(oneUser.getUserId());
            RecommendItem recommendItem = new RecommendItem();
            recommendItem.setUserId(oneUser.getUserId());
            recommendItem.setGender(oneUser.getGender());
            recommendItem.setSelfIntro(oneUser.getSelfIntro());
            recommendItem.setVipLevel(oneUser.getVipLevel());
            recommendItem.setName(oneUser.getName());

            try {
                recommendItem.setAge(DateUtil.getAge(oneUser.getBirthday()));
            } catch (Exception e) {
                e.printStackTrace();
                recommendItem.setAge(0);
            }

            if (details != null) {
                recommendItem.setDomicile(details.getDomicile());
                recommendItem.setHeight(details.getHeight());
                recommendItem.setEducation(details.getEducation());
                recommendItem.setMonthlySalary(details.getMonthlySalary());
                recommendItem.setWeight(details.getWeight());
                recommendItem.setHobby(details.getHobby());
                recommendItem.setLoveDeclaration(details.getLoveDeclaration());
            }
            recommendItems.add(recommendItem);
        }

        return recommendItems;
    }
*/
    @Override
    public int followUser(int userId, int followedUser) {

        if (userMapper.selectByPrimaryKey(followedUser)==null)
            return 5;

        FollowingKey followingKey = new FollowingKey();
        followingKey.setUserFollowed(followedUser);
        followingKey.setUserFollowing(userId);
        if (followingMapper.selectByPrimaryKey(followingKey) != null) {
            if (followingMapper.deleteByPrimaryKey(followingKey) == 1)
                return 1;
            else return 0;
        }

        Following following = new Following();
        following.setUserFollowing(userId);
        following.setUserFollowed(followedUser);
        following.setFollowTime(new Date(System.currentTimeMillis()));

        return followingMapper.insert(following);
    }

    @Override
    public List<RecommendItem> getFollowingList(int userId, int offset, int count) {

        FollowingExample followingExample=new FollowingExample();
        followingExample.setOrderByClause("follow_time limit "+offset+" , "+count);
        followingExample.or().andUserFollowingEqualTo(userId);

        List<Following> followings=followingMapper.selectByExample(followingExample);

        List<RecommendItem> recommendItems=new ArrayList<>();

        for (Following following : followings) {

            User oneUser = userMapper.selectByPrimaryKey(following.getUserFollowed());

            DetailsWithBLOBs details = detailsMapper.selectByPrimaryKey(oneUser.getUserId());
            RecommendItem recommendItem = new RecommendItem();
            recommendItem.setUserId(oneUser.getUserId());
            recommendItem.setGender(oneUser.getGender());
            recommendItem.setSelfIntro(oneUser.getSelfIntro());
            recommendItem.setVipLevel(oneUser.getVipLevel());
            recommendItem.setName(oneUser.getName());

            try {
                recommendItem.setAge(DateUtil.getAge(oneUser.getBirthday()));
            } catch (Exception e) {
                e.printStackTrace();
                recommendItem.setAge(0);
            }

            if (details != null) {
                recommendItem.setDomicile(details.getDomicile());
                recommendItem.setHeight(details.getHeight());
                recommendItem.setEducation(details.getEducation());
                recommendItem.setMonthlySalary(details.getMonthlySalary());
                recommendItem.setWeight(details.getWeight());
                recommendItem.setHobby(details.getHobby());
                recommendItem.setLoveDeclaration(details.getLoveDeclaration());
            }
            recommendItems.add(recommendItem);
        }

        return recommendItems;
    }

    @Override
    public List<RecommendItem> getFansList(int userId, int offset, int count) {
        FollowingExample followingExample = new FollowingExample();

        followingExample.setOrderByClause("follow_time limit " + offset + " , " + count);
        followingExample.or().andUserFollowedEqualTo(userId);
        List<Following> followings = followingMapper.selectByExample(followingExample);

        List<RecommendItem> recommendItems = new ArrayList<>();
        for (Following following : followings) {

            User oneUser = userMapper.selectByPrimaryKey(following.getUserFollowing());

            DetailsWithBLOBs details = detailsMapper.selectByPrimaryKey(oneUser.getUserId());
            RecommendItem recommendItem = new RecommendItem();
            recommendItem.setUserId(oneUser.getUserId());
            recommendItem.setGender(oneUser.getGender());
            recommendItem.setSelfIntro(oneUser.getSelfIntro());
            recommendItem.setVipLevel(oneUser.getVipLevel());
            recommendItem.setName(oneUser.getName());

            try {
                recommendItem.setAge(DateUtil.getAge(oneUser.getBirthday()));
            } catch (Exception e) {
                e.printStackTrace();
                recommendItem.setAge(0);
            }

            if (details != null) {
                recommendItem.setDomicile(details.getDomicile());
                recommendItem.setHeight(details.getHeight());
                recommendItem.setEducation(details.getEducation());
                recommendItem.setMonthlySalary(details.getMonthlySalary());
                recommendItem.setWeight(details.getWeight());
                recommendItem.setHobby(details.getHobby());
                recommendItem.setLoveDeclaration(details.getLoveDeclaration());
            }
            recommendItems.add(recommendItem);
        }

        return recommendItems;
    }

    @Override
    public boolean checkFollowing(int userId, int followedUser) {
        FollowingKey followingKey=new FollowingKey();
        followingKey.setUserFollowing(userId);
        followingKey.setUserFollowed(followedUser);
        //List<Following> followings=followingMapper.selectByPrimaryKey(followingKey);

        return followingMapper.selectByPrimaryKey(followingKey)!=null;
    }


    @Override
    public int sendMessage(int userId, int toUserId, String content) {

        Message message=new Message();

        message.setUserId(userId);
        message.setSendTo(toUserId);

        message.setContent(content);

        message.setSendTime(new Date(System.currentTimeMillis()));

        message.setStatus((byte)0);

        return messageMapper.insert(message);
    }

    @Override
    public List<Message> getMessageList(int userId, int offset, int count) {

        MessageExample messageExample=new MessageExample();

        messageExample.setOrderByClause("send_time DESC limit "+offset+" , "+count);

        messageExample.or().andSendToEqualTo(userId).andStatusNotEqualTo((byte)2);

        List<Message> messages=messageMapper.selectByExampleWithBLOBs(messageExample);

        if (messages==null||messages.size()==0)
            return null;

        for (Message message:messages){

            message.setFromUser(userMapper.selectByPrimaryKey(message.getUserId()));

        }

        return messages;
    }

    @Override
    public int deleteMessage(int userId, int messageId) {

        Message message=messageMapper.selectByPrimaryKey(messageId);

        if (message==null||message.getMessageId()==0)
            return 6;

        if (message.getUserId()==userId){
            if (message.getStatus()==1)
                return 6;
            message.setStatus((byte)(message.getStatus()+1));
        }else if (message.getSendTo()==userId){
            if (message.getStatus()==2)
                return 6;
            message.setStatus((byte)(message.getStatus()+2));
        }else
            return -2;


        if (message.getStatus()>=3)
            return messageMapper.deleteByPrimaryKey(messageId);

        return messageMapper.updateByPrimaryKey(message);
    }
}
